<template>
    <div class="login">
        <div class="leftBox">
            <div class="logoBox">
                <img src="@/assets/logo.png" />
                <div class="logoBoxTit">
                    <div>贵州乌江水电开发有限责任公司</div>
                    <div>黔西乌江水电新能源有限公司</div>
                </div>
            </div>
            <div class="anaBox">
                随着风电产业的迅速发展，项目的规模和复杂度不断提 升，导致施工难度增大，对项目全过程的管理要求也日益严 格，为了实现项目的安全、高效和规范化管理，结合中国华 电集团有限公司《外委工程与外协用工安全管理办法》及《关于进一步加强外委工程与外协用工安全管理的通知》，风电安全管控系统通过整合各类资源和信息， 旨在构建 一个全面、集成的管理平台，提高管理效率、降低成本、增 强安全保障，为安全管理决策提供有力支持。
            </div>
            <div class="writerBox">
                <!-- <img src="@/assets/logo.png" /> -->
                <div class="info">
                    <!-- <div class="name">华电新能</div> -->
                    <div class="position">黔西乌江水电新能源有限公司</div>
                </div>
            </div>
        </div>
        <div class="rightBox">
            <div class="loginBox">
                <div class="title">花溪将军山风电项目安全管控提升技术平台</div>
                <el-form ref="loginForm" :model="loginForm">
                    <el-form-item prop="username" label=""
                        :rules="[{ required: true, message: '请输入用户名址', trigger: 'blur' }]">
                        <div class="label">用户名</div>
                        <el-input placeholder="用户名" type="text" v-model="loginForm.username"></el-input>
                    </el-form-item>
                    <el-form-item prop="password" label=""
                        :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]">
                        <div class="label">密码</div>
                        <el-input placeholder="密码" type="password" v-model="loginForm.password"></el-input>
                    </el-form-item>
                </el-form>
                <el-button class="loginBtn" :loading="btnLoading" type="primary" @click="handleSubmit">登录</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { goIn, getBoardProjectList, getDeptUserRules, getUnreadMsgNum } from "@/api/api"
export default {
    name: "login",
    data() {
        return {
            loginForm: {},
            btnLoading: false,
        }
    },
    created() {
        window.addEventListener("keyup", this.keyUp)
    },
    methods: {
        handleSubmit() {
            this.$refs.loginForm.validate(async (valid) => {
                if (valid) {
                    this.btnLoading = true
                    let params = {
                        username: this.loginForm.username,
                        password: this.loginForm.password,
                    }
                    // 登录
                    await goIn(params).then((res) => {
                        if (res.code == 200) {
                            this.btnLoading = false
                            localStorage.setItem("username", res.data.nickname)
                            localStorage.setItem("userphone", res.data.phone)
                            localStorage.setItem("userId", res.data.userId)
                            localStorage.setItem("loginMethod", res.data.loginMethod)
                            document.onkeydown = undefined
                        } else {
                            this.$Message.warning(res.msg)
                            this.btnLoading = false
                        }
                    })
                    .catch((error) => {
                        this.btnLoading = false
                    })

                    // 获取所属项目
                    let deptId = await getBoardProjectList().then((res) => {
                        if (res.code == 200) {
                            localStorage.setItem("project_list", JSON.stringify(res.data.list))
                            localStorage.setItem("deptId", res.data.list[0].deptId)
                            return res.data.list[0].deptId
                        } else {
                            this.$Message.warning(res.msg)
                        }
                    })

                    // 获取用户权限
                    await getDeptUserRules({ deptId }).then(res => {
                        if (res.code != 200) {
                            this.$Message.warning(res.msg);
                            return;
                        }
                        const linkArray = res.data.list;
                        const btnPermissions = []; // 按钮权限
                        const sysPermissions = []; // 系统权限
                        const nodeMap = new Map(); // 节点映射表
                        const rootNodes = [];     // 根节点列表

                        // 第一遍遍历：创建节点并分类
                        linkArray.forEach(item => {
                            // 收集权限
                            if (item.type === 3) {
                                btnPermissions.push(item.code)
                                return
                            };
                            if (item.type === 1) sysPermissions.push(item.code);

                            // 创建节点对象
                            const node = {
                                id: item.ruleId,
                                pid: item.pid,
                                index: item.index,
                                code: item.code,
                                supervise: item.supervise,
                                appScene: item.appScene,
                                openStatus: item.openStatus,
                                type: item.type,
                                pageType: item.pageType || 1,
                                selectIcon: item.iconPath,
                                unselectIcon: item.iconUnselect,
                                children: []
                            };

                            // 根节点特殊处理
                            if (item.pid === 0) {
                                Object.assign(node, {
                                    title: item.shortName,
                                    content: item.content,
                                    url: item.path,
                                    name: item.shortName // 为searchOptions准备
                                });
                                rootNodes.push(node);
                            } else {
                                Object.assign(node, {
                                    name: item.shortName,
                                    url: item.path
                                });
                            }

                            // 存入映射表
                            nodeMap.set(item.ruleId, node);
                        });
                        // 第二遍遍历：构建树形结构
                        linkArray.forEach(item => {
                            if (item.type === 3) return; // 跳过按钮
                            if (item.pid === 0) return; // 跳过根节点

                            const node = nodeMap.get(item.ruleId);
                            const parent = nodeMap.get(item.pid);

                            if (parent) {
                                parent.children.push(node);
                            }
                        });

                        // 排序处理
                        const sortChildren = nodes => {
                            return nodes.sort((a, b) => a.index - b.index).map(node => {
                                if (node.children && node.children.length > 0) {
                                    node.children = sortChildren(node.children);
                                }
                                return node;
                            });
                        };

                        // 构建最终树形结构
                        const sortedTree = sortChildren(rootNodes);

                        // 存储按钮权限信息
                        localStorage.setItem("arr", JSON.stringify(btnPermissions));
                        // 存储模块权限
                        this.$store.commit("setModalArr", sysPermissions);

                        // 过滤导航项
                        let navs = sortedTree.filter(v =>
                            !v.code.includes("esgcc") && !v.code.includes("gscx")
                        );
                        // 存储所有权限
                        this.$store.commit("setRuleList", navs);

                    })

                    // 获取未读消息数量
                    await getUnreadMsgNum({ deptId }).then(res=>{
                        if (res.code == 200) {
                            this.$store.commit("setMsgNum", res.data.total)
                        }
                    })

                    localStorage.setItem("topMenuActive", "home")
                    localStorage.removeItem("routeHistory")
                    this.$router.push({
                        path: "/home",
                    })
                }
            })
        },

        /* 大小键盘Enter键盘登陆 */
        keyUp(e) {
            if (e.keyCode == 13) {
                this.handleSubmit()
            }
        },

        /* 跳转工信网 */
        tobeian() {
            window.open("https://beian.miit.gov.cn", "_blank")
        },
    },
    destroyed() {
        window.removeEventListener("keyup", this.keyUp, false)
    },
}
</script>
<style scoped lang="scss">
.login {
    height: 100%;
    display: flex;

    .leftBox {
        width: 560px;
        height: 100%;
        padding: 50px 0 50px 50px;
        box-sizing: border-box;
        background: url("~@/assets/images/login/login_left_bg.jpg") no-repeat;
        background-size: 100% 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .logoBox {
            display: flex;
            align-items: center;
            gap: 10px;

            img {
                height: 52px;
            }

            .logoBoxTit {
                font-size: 14px;
                color: #cccccc;
            }
        }

        .anaBox {
            width: 445px;
            font-size: 20px;
            color: #ffffff;
            line-height: 36px;
        }

        .writerBox {
            display: flex;
            align-items: center;

            img {
                margin-right: 10px;
                width: 60px;
                height: 60px;
                border-radius: 50%;
            }

            .info {
                .name {
                    font-size: 20px;
                    color: #ffffff;
                }

                .position {
                    font-size: 14px;
                    color: #cccccc;
                }
            }
        }
    }

    .rightBox {
        flex: 1;
        position: relative;

        .loginBox {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 470px;

            .title {
                margin-bottom: 50px;
                font-size: 36px;
                color: #333333;
                font-weight: 700;
                text-align: center;
                line-height: 1;
            }

            .label {
                font-size: 16px;
                color: #a0a3a1;
            }

            >>>.el-input__inner {
                height: 50px;
            }

            .loginBtn {
                margin-top: 20px;
                width: 100%;
                height: 55px;
                font-size: 18px;
                color: #ffffff;
                text-align: center;
                border-radius: 30px;
                background-color: #337df8;
            }
        }
    }
}
</style>
